package com.ruoyi.web.controller.system;

import com.ruoyi.IOT.requset.PointRequest;
import com.ruoyi.IOT.service.GatherService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.TPointMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.*;

/**
 * ********************温室前端接口*********************
 *
 * @author ruoyi
 * @date 2019-09-01
 */
@Controller
@RequestMapping("/system/front_wenshi")
public class FrontWenShiController extends BaseController {
    private String prefix = "system/front_wenshi";

    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private INcPengInfoService pengInfoService;
    @Autowired
    private INcStandardService standardService;
    @Autowired
    private INcPlanService planService;
    @Autowired
    private INcWorkMirrorService workMirrorService;
    @Autowired
    private INcStageMirrorService stageMirrorService;
    @Autowired
    private TPointMapper tPointMapper;
    @Autowired
    private ITPointService pointService;
    @Autowired
    private GatherService gatherService;


    @Resource
    @Qualifier("primaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    private String prefix_screen = "system/screen";

    /*温室管理*/
    @GetMapping("/greenhouseManagement")
    public String greenhouseManagement(Integer type, ModelMap mmap) {
        int planCount = 0;

        //1、计算温室数量
        SysDept dept = new SysDept();
        dept.setType(3);
        dept.setAncestors("101");//温室
        List<SysDept> list = sysDeptService.selectDeptList(dept);
        List<SysDept> result = new ArrayList<>();
        List<SysDept> myResult = new ArrayList<>();
        //大棚
        for (SysDept d : list) {
            if (d.getAncestors().split(",").length == 4) {
                result.add(d);
            }
        }
        //根据大棚 去找计划数量
        for (SysDept d : result) {
            Integer count = pengInfoService.getPlaningCount(d.getDeptId());
            count = count == null ? 0 : count;
            d.setPlanCount(count);
            planCount += count;
            //查找每个温室的传感数据
            Map<String, Object> map = pointService.listSensorChartInfo(d);
            if (map != null && map.get("tp_id") == null) {
                map.put("tp_id", -100);
            }
            d.setParams(map);

        }
        try {
            //对结果进行处理
            pointService.calcFailData(result);
        } catch (Exception e) {

        }
        mmap.put("pengs", result);
        mmap.put("planCount", planCount);
        mmap.put("pengCount", result.size());


        return prefix + "/greenhouseManagement-2";
    }





    /*育苗*/
    @GetMapping("/seedlingManagement")
    public String seedlingManagement(NcPlan plan, String beginTime, String endTime, ModelMap mmap) {
        plan.setPlanType(1);
        if (StringUtils.isNotEmpty(beginTime)) {
            plan.getParams().put("beginTime", beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            plan.getParams().put("endTime", endTime);
        }
        //按时间查询育苗计划数量
        /*状态 1:待生成订单 2：待执行 3.在执行 4.已完成*/
        Map statusCount = planService.getStatusCount(plan);

        mmap.put("beginTime", beginTime);
        mmap.put("statusCount", statusCount);
        mmap.put("endTime", endTime);
        mmap.put("caiClass", planService.getBigCaiClass(plan));


        return prefix + "/newGiantMountain";
    }

    /*植保请求记录*/
    @GetMapping("/ncXiaoduLogs")
    public String ncZhibaoLogs(NcPlan plan, ModelMap mmap) {
        return prefix + "/ncXiaoduLogs";
    }

    /*育苗计划*/
    @GetMapping("/frontYuMiaoCount")
    public String frontOrderCf(String status, String beginTime, String endTime, String ancestors, ModelMap mmap) {

        mmap.put("status", status);
        mmap.put("ancestors", ancestors);
        mmap.put("beginTime", beginTime);
        mmap.put("endTime", endTime);
        return prefix + "/frontYuMiaoCount";
    }

    /*生产计划*/
    @GetMapping("/frontPlans")
    public String frontPlans(String deptId, ModelMap mmap) {

        mmap.put("deptId", deptId);
        return prefix + "/frontPlans";
    }

    /*计划详情*/
    @GetMapping("/planDetail")
    public String planDetail(Long planId, String planType, ModelMap mmap) {
        planService.planDetail(planId, planType, mmap);
        return prefix + "/standerDetail";
    }

    /*阶段 或者 工作 详情*/
    @GetMapping("/detail")
    public String detail(Integer type, Long id, String workDate, ModelMap mmap) {
        //1 :工作详情（镜像） 2：阶段详情（镜像）
        if (type == 2) {
            NcStageMirror stage = stageMirrorService.selectNcStageMirrorById(id);
            mmap.put("stage", stage);
            return prefix + "/detail-stage";
        } else if (type == 1) {
            NcWorkMirror work = workMirrorService.selectNcWorkMirrorById(id);
            mmap.put("work", work);
            mmap.put("workDate", workDate);
            return prefix + "/detail-work";
        } else {
            return "main";
        }

    }

    /**
     * 查询温室温度湿度
     *
     * @param room 温室号
     * @param mmap
     * @return
     */
    @GetMapping("/showWenshiWeather/{room}")
    public String showWenshiWeather(@PathVariable("room") String room, ModelMap mmap) {

        //获取登录用户
        SysUser sysUser = ShiroUtils.getSysUser();

        mmap.put("user", sysUser);

        //TODO 删除
        sysUser.setDeptId(103L);

        //查询当前用户部门
        SysDept sysDept = sysDeptService.selectDeptById(sysUser.getDeptId());


        //根据uuid查询point中的部门point
        TPoint point = new TPoint();
        point.setUuid(sysDept.getUuid());
        //部门
        List<TPoint> dept = pointService.selectTPointList(point);


        Long tpId = dept.get(0).getTpId();
        TPoint wenshi = new TPoint();
        wenshi.setTpPid(tpId);
        //温室
        List<TPoint> wenshiPList = pointService.selectTPointList(wenshi);

//        wenshiPList.removeIf(thisPoint -> !room.equals(thisPoint.getTpName().substring(2, thisPoint.getTpName().length())));

        TPoint thisWenshi = new TPoint();
        ;
        for (TPoint thisPoint : wenshiPList) {

            //找到温室
            String tpName = thisPoint.getTpName();
            String wenshiRoom = tpName.substring(2, tpName.length());
            //根据温室号查找温室
            if (room.equals(wenshiRoom)) {
                thisWenshi.setTpPid(thisPoint.getTpId());
            }
        }
        thisWenshi.setTpType(3L);

        //查询温室下的所有传感设备


        List<TPoint> tPoints = pointService.selectTPointList(thisWenshi);

        //空气温度
        List<String> airTemperature = new ArrayList<>();
        //土壤温度
        List<String> soilTemperature = new ArrayList<>();

        //空气湿度
        List<String> airMoisture = new ArrayList<>();
        //土壤湿度
        List<String> soilMoisture = new ArrayList<>();


        if (!tPoints.isEmpty()) {

            TPoint thisP = tPoints.get(0);
            String deviceId = thisP.getDeviceId();

            PointRequest pr = new PointRequest();
            pr.setDeviceId(deviceId);
            pr.setTp_id(thisP.getTpId().intValue());
            Map<String, Object> todayInfo = gatherService.listSensorInfoFirst(pr).get(0);


            //一周数据
            String[] days = last7Day(Calendar.getInstance());


            for (String thisDay : days) {
                pr.setBeginTime(thisDay);
                List<Map<String, Object>> maps1 = gatherService.listInfo(pr);
                if (maps1.size() != 0) {

                    //空气温度
                    Object Channel1 = maps1.get(0).get("Channel1");
                    //空气湿度
                    Object Channel2 = maps1.get(0).get("Channel2");
                    //土壤湿度
                    Object Channel5 = maps1.get(0).get("Channel5");
                    //土壤温度
                    Object Channel6 = maps1.get(0).get("Channel6");

                    airTemperature.add((String) Channel1);
                    soilTemperature.add((String) Channel6);
                    airMoisture.add((String) Channel2);
                    soilMoisture.add((String) Channel5);

                } else {
                    airTemperature.add("0");
                    soilTemperature.add("0");
                    airMoisture.add("0");
                    soilMoisture.add("0");
                }


            }

            mmap.put("days", days);
            mmap.put("todayInfo", todayInfo);
            mmap.put("airTemperature", airTemperature);
            mmap.put("soilTemperature", soilTemperature);
            mmap.put("airMoisture", airMoisture);
            mmap.put("soilMoisture", soilMoisture);


        }


        return prefix_screen + "/wenshi-1";
    }


    /**
     * 屏保 日光温室种植任务
     *
     * @param mmap
     * @return
     */
    @GetMapping("/showPlanLandType4")
    public String showPlanLandType4(ModelMap mmap) {

        //获取登录用户
        SysUser sysUser = ShiroUtils.getSysUser();

        //查询当前用户部门
        SysDept sysDept = sysDeptService.selectDeptById(sysUser.getDeptId());

        //获取日光温室种植计划
        NcPlan ncPlan = new NcPlan();
        ncPlan.setTeam(sysDept.getDeptId() + "");
        List<NcPlan> plans = planService.showPlanLandType4(ncPlan);


        //查询日光温室种植计划不为空
        if (!plans.isEmpty()) {
            for (NcPlan plan : plans) {

                //计划是否匹配标准 1:匹配 2：未匹配
                String hasStandard = plan.getHasStandard();

                if ("1".equals(hasStandard)) {

                    //计划对应标准
                    NcStandard standard = standardService.selectNcStandardById(plan.getStandardId());

                    if (standard != null) {
                        plan.setStandard(standard);
                    }

                }

                //计划对应阶段
                NcStageMirror stageMirror = new NcStageMirror();
                stageMirror.setPlanId(plan.getPlanId());
                List<NcStageMirror> ncStageMirrors = stageMirrorService.selectNcStageMirrorList(stageMirror);
                plan.setStages(ncStageMirrors);
            }
        }

        mmap.put("user", ShiroUtils.getSysUser());
        mmap.put("plans", plans);
        return prefix_screen + "/wenshi-2";
    }


    public String[] last7Day(Calendar cal) {
        String[] last7Day = new String[7];
        for (int i = 0; i < 7; i++) {
            if (cal.get(Calendar.MONTH) + 1 < 10) {
                if (cal.get(Calendar.DATE) < 10) {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1) + "-0" + (cal.get(Calendar.DATE));
                } else {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1) + "-" + (cal.get(Calendar.DATE));
                }
            } else {
                if (cal.get(Calendar.DATE) < 10) {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-0" + (cal.get(Calendar.DATE));
                } else {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + (cal.get(Calendar.DATE));
                }

            }
            cal.set(Calendar.DATE, cal.get(Calendar.DATE) - 1); //逐次往前推1天*/

        }
        return last7Day;
    }


}
